const Reminder = require('../models/Reminder');
const mongoose = require('mongoose');
const { getNextOccurrence } = require('../utils/reminderUtils');

/**
 * 获取用户的所有提醒
 */
exports.getReminders = async (req, res) => {
  try {
    const userId = req.user._id;
    const type = req.query.type; // 可选过滤参数
    const enabled = req.query.enabled; // 可选过滤 (true/false)
    
    // 构建查询条件
    const query = { userId };
    
    if (type) {
      query.type = type;
    }
    
    if (enabled !== undefined) {
      query.enabled = enabled === 'true';
    }
    
    // 获取提醒列表
    const reminders = await Reminder.find(query).sort({ priority: -1, hour: 1, minute: 1 });
    
    res.json({
      success: true,
      data: reminders
    });
  } catch (error) {
    console.error('获取提醒列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取提醒列表失败',
      error: error.message
    });
  }
};

/**
 * 获取今天需要提醒的项目
 */
exports.getTodayReminders = async (req, res) => {
  try {
    const userId = req.user._id;
    
    // 获取今天是星期几 (0-6, 0代表周日)
    const today = new Date().getDay();
    
    // 查询条件：用户ID、启用状态为true、重复日中包含今天或为空
    const query = {
      userId,
      enabled: true,
      $or: [
        { repeatDays: { $in: [today] } },
        { repeatDays: { $size: 0 } } // 空数组表示不重复，但如果是今天创建的，也应该提醒
      ]
    };
    
    // 获取提醒列表
    const reminders = await Reminder.find(query).sort({ priority: -1, hour: 1, minute: 1 });
    
    res.json({
      success: true,
      data: reminders
    });
  } catch (error) {
    console.error('获取今日提醒失败:', error);
    res.status(500).json({
      success: false,
      message: '获取今日提醒失败',
      error: error.message
    });
  }
};

/**
 * 获取即将到来的提醒
 */
exports.getUpcomingReminders = async (req, res) => {
  try {
    const userId = req.user._id;
    const limit = parseInt(req.query.limit) || 5;
    
    // 查询条件：用户ID、启用状态为true、未完成
    const query = {
      userId,
      enabled: true,
      isCompleted: false
    };
    
    // 获取提醒列表，限制返回数量
    const reminders = await Reminder.find(query)
      .sort({ priority: -1, hour: 1, minute: 1 })
      .limit(limit);
    
    res.json({
      success: true,
      data: reminders
    });
  } catch (error) {
    console.error('获取即将到来的提醒失败:', error);
    res.status(500).json({
      success: false,
      message: '获取即将到来的提醒失败',
      error: error.message
    });
  }
};

/**
 * 获取提醒统计数据
 */
exports.getReminderStats = async (req, res) => {
  try {
    const userId = req.user._id;
    
    // 聚合查询统计数据
    const stats = await Reminder.aggregate([
      { $match: { userId: mongoose.Types.ObjectId(userId) } },
      {
        $group: {
          _id: null,
          total: { $sum: 1 },
          completed: { $sum: { $cond: [{ $eq: ['$isCompleted', true] }, 1, 0] } },
          active: { $sum: { $cond: [{ $and: [{ $eq: ['$enabled', true] }, { $eq: ['$isCompleted', false] }] }, 1, 0] } },
          highPriority: { $sum: { $cond: [{ $and: [{ $eq: ['$priority', 3] }, { $eq: ['$isCompleted', false] }] }, 1, 0] } }
        }
      }
    ]);
    
    // 类型分布统计
    const typeDistribution = await Reminder.aggregate([
      { $match: { userId: mongoose.Types.ObjectId(userId) } },
      {
        $group: {
          _id: '$type',
          count: { $sum: 1 }
        }
      }
    ]);
    
    // 组织返回数据
    const result = {
      total: 0,
      completed: 0,
      active: 0,
      highPriority: 0,
      completionRate: 0,
      typeDistribution: []
    };
    
    if (stats.length > 0) {
      result.total = stats[0].total;
      result.completed = stats[0].completed;
      result.active = stats[0].active;
      result.highPriority = stats[0].highPriority;
      result.completionRate = result.total > 0 ? Math.round((result.completed / result.total) * 100) : 0;
    }
    
    // 类型映射
    const typeNames = {
      'medication': '用药提醒',
      'measurement': '测量提醒',
      'exercise': '运动提醒',
      'water': '饮水提醒',
      'assessment': '评估提醒'
    };
    
    // 处理类型分布数据
    result.typeDistribution = typeDistribution.map(item => ({
      type: item._id,
      name: typeNames[item._id] || '其他提醒',
      count: item.count,
      percentage: result.total > 0 ? Math.round((item.count / result.total) * 100) : 0
    }));
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('获取提醒统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取提醒统计失败',
      error: error.message
    });
  }
};

/**
 * 获取单条提醒详情
 */
exports.getReminderById = async (req, res) => {
  try {
    const userId = req.user._id;
    const reminderId = req.params.id;
    
    if (!mongoose.Types.ObjectId.isValid(reminderId)) {
      return res.status(400).json({
        success: false,
        message: '无效的提醒ID'
      });
    }
    
    // 查询提醒详情
    const reminder = await Reminder.findOne({
      _id: reminderId,
      userId
    });
    
    if (!reminder) {
      return res.status(404).json({
        success: false,
        message: '提醒不存在'
      });
    }
    
    res.json({
      success: true,
      data: reminder
    });
  } catch (error) {
    console.error('获取提醒详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取提醒详情失败',
      error: error.message
    });
  }
};

/**
 * 创建新提醒
 */
exports.createReminder = async (req, res) => {
  try {
    const userId = req.user._id;
    
    // 验证必要字段
    const { title, type, hour, minute } = req.body;
    
    if (!title) {
      return res.status(400).json({
        success: false,
        message: '提醒标题不能为空'
      });
    }
    
    if (hour === undefined || minute === undefined) {
      return res.status(400).json({
        success: false,
        message: '提醒时间不能为空'
      });
    }
    
    // 创建提醒数据
    const reminderData = {
      userId,
      title,
      type: type || 'medication',
      hour: parseInt(hour),
      minute: parseInt(minute),
      repeatDays: req.body.repeatDays || [0, 1, 2, 3, 4, 5, 6], // 默认每天
      enabled: req.body.enabled !== undefined ? req.body.enabled : true,
      priority: req.body.priority || 2,
      note: req.body.note || ''
    };
    
    // 计算下次提醒时间
    reminderData.nextOccurrence = getNextOccurrence(
      reminderData.hour,
      reminderData.minute,
      reminderData.repeatDays
    );
    
    // 创建提醒
    const reminder = await Reminder.create(reminderData);
    
    res.status(201).json({
      success: true,
      message: '提醒创建成功',
      data: reminder
    });
  } catch (error) {
    console.error('创建提醒失败:', error);
    res.status(500).json({
      success: false,
      message: '创建提醒失败',
      error: error.message
    });
  }
};

/**
 * 更新提醒
 */
exports.updateReminder = async (req, res) => {
  try {
    const userId = req.user._id;
    const reminderId = req.params.id;
    
    if (!mongoose.Types.ObjectId.isValid(reminderId)) {
      return res.status(400).json({
        success: false,
        message: '无效的提醒ID'
      });
    }
    
    // 查找提醒
    const reminder = await Reminder.findOne({
      _id: reminderId,
      userId
    });
    
    if (!reminder) {
      return res.status(404).json({
        success: false,
        message: '提醒不存在'
      });
    }
    
    // 准备更新数据
    const updateData = {};
    
    // 更新基本信息
    if (req.body.title !== undefined) updateData.title = req.body.title;
    if (req.body.type !== undefined) updateData.type = req.body.type;
    if (req.body.hour !== undefined) updateData.hour = parseInt(req.body.hour);
    if (req.body.minute !== undefined) updateData.minute = parseInt(req.body.minute);
    if (req.body.repeatDays !== undefined) updateData.repeatDays = req.body.repeatDays;
    if (req.body.enabled !== undefined) updateData.enabled = req.body.enabled;
    if (req.body.priority !== undefined) updateData.priority = parseInt(req.body.priority);
    if (req.body.note !== undefined) updateData.note = req.body.note;
    
    // 如果时间或重复日期发生变化，更新下次提醒时间
    if (
      updateData.hour !== undefined || 
      updateData.minute !== undefined || 
      updateData.repeatDays !== undefined
    ) {
      const hour = updateData.hour !== undefined ? updateData.hour : reminder.hour;
      const minute = updateData.minute !== undefined ? updateData.minute : reminder.minute;
      const repeatDays = updateData.repeatDays !== undefined ? updateData.repeatDays : reminder.repeatDays;
      
      updateData.nextOccurrence = getNextOccurrence(hour, minute, repeatDays);
    }
    
    // 更新时间
    updateData.updatedAt = new Date();
    
    // 执行更新
    const updatedReminder = await Reminder.findByIdAndUpdate(
      reminderId,
      { $set: updateData },
      { new: true }
    );
    
    res.json({
      success: true,
      message: '提醒更新成功',
      data: updatedReminder
    });
  } catch (error) {
    console.error('更新提醒失败:', error);
    res.status(500).json({
      success: false,
      message: '更新提醒失败',
      error: error.message
    });
  }
};

/**
 * 删除提醒
 */
exports.deleteReminder = async (req, res) => {
  try {
    const userId = req.user._id;
    const reminderId = req.params.id;
    
    if (!mongoose.Types.ObjectId.isValid(reminderId)) {
      return res.status(400).json({
        success: false,
        message: '无效的提醒ID'
      });
    }
    
    // 查找并删除提醒
    const reminder = await Reminder.findOneAndDelete({
      _id: reminderId,
      userId
    });
    
    if (!reminder) {
      return res.status(404).json({
        success: false,
        message: '提醒不存在'
      });
    }
    
    res.json({
      success: true,
      message: '提醒删除成功'
    });
  } catch (error) {
    console.error('删除提醒失败:', error);
    res.status(500).json({
      success: false,
      message: '删除提醒失败',
      error: error.message
    });
  }
};

/**
 * 标记提醒为已完成
 */
exports.completeReminder = async (req, res) => {
  try {
    const userId = req.user._id;
    const reminderId = req.params.id;
    
    if (!mongoose.Types.ObjectId.isValid(reminderId)) {
      return res.status(400).json({
        success: false,
        message: '无效的提醒ID'
      });
    }
    
    // 查找提醒
    const reminder = await Reminder.findOne({
      _id: reminderId,
      userId
    });
    
    if (!reminder) {
      return res.status(404).json({
        success: false,
        message: '提醒不存在'
      });
    }
    
    // 添加完成记录
    const completedAt = req.body.completedAt ? new Date(req.body.completedAt) : new Date();
    
    const completion = {
      date: completedAt,
      status: 'completed',
      completedAt
    };
    
    // 更新提醒状态
    const updateData = {
      $push: { completionHistory: completion },
      $set: {
        isCompleted: true,
        updatedAt: new Date()
      }
    };
    
    // 执行更新
    const updatedReminder = await Reminder.findByIdAndUpdate(
      reminderId,
      updateData,
      { new: true }
    );
    
    res.json({
      success: true,
      message: '提醒已标记为完成',
      data: updatedReminder
    });
  } catch (error) {
    console.error('标记提醒完成失败:', error);
    res.status(500).json({
      success: false,
      message: '标记提醒完成失败',
      error: error.message
    });
  }
};

/**
 * 延迟提醒
 */
exports.snoozeReminder = async (req, res) => {
  try {
    const userId = req.user._id;
    const reminderId = req.params.id;
    
    if (!mongoose.Types.ObjectId.isValid(reminderId)) {
      return res.status(400).json({
        success: false,
        message: '无效的提醒ID'
      });
    }
    
    // 查找提醒
    const reminder = await Reminder.findOne({
      _id: reminderId,
      userId
    });
    
    if (!reminder) {
      return res.status(404).json({
        success: false,
        message: '提醒不存在'
      });
    }
    
    // 计算延迟时间
    const delayMinutes = parseInt(req.body.delayMinutes) || 10; // 默认延迟10分钟
    const now = new Date();
    const snoozeUntil = new Date(now.getTime() + delayMinutes * 60000);
    
    // 添加延迟记录
    const snoozedRecord = {
      date: now,
      status: 'snoozed',
      completedAt: null
    };
    
    // 更新提醒状态
    const updateData = {
      $push: { completionHistory: snoozedRecord },
      $set: {
        nextOccurrence: snoozeUntil,
        updatedAt: now
      }
    };
    
    // 执行更新
    const updatedReminder = await Reminder.findByIdAndUpdate(
      reminderId,
      updateData,
      { new: true }
    );
    
    res.json({
      success: true,
      message: '提醒已延迟',
      data: updatedReminder
    });
  } catch (error) {
    console.error('延迟提醒失败:', error);
    res.status(500).json({
      success: false,
      message: '延迟提醒失败',
      error: error.message
    });
  }
};

/**
 * 获取提醒类型列表
 */
exports.getReminderTypes = async (req, res) => {
  try {
    // 提醒类型列表
    const types = [
      { value: 'medication', label: '药物提醒' },
      { value: 'measurement', label: '测量提醒' },
      { value: 'exercise', label: '运动提醒' },
      { value: 'water', label: '饮水提醒' },
      { value: 'assessment', label: '评估提醒' }
    ];
    
    res.json({
      success: true,
      data: types
    });
  } catch (error) {
    console.error('获取提醒类型失败:', error);
    res.status(500).json({
      success: false,
      message: '获取提醒类型失败',
      error: error.message
    });
  }
}; 